package com.newa.dao;

import java.util.ArrayList;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.newa.beans.Orderu;

public class DAOOrder {
	private Session session;

	public DAOOrder(Session session) {
		super();
		this.session = session;
	}
	

	public ArrayList<Orderu> getAllOrders(){
		Transaction tx = session.beginTransaction();
		try {
			Query qu = session.createQuery("from Orderu");
			ArrayList<Orderu> res = new ArrayList<Orderu>(qu.list());
			return res;
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}
	}
	
	public boolean createOrder(Orderu or) {
		Transaction tx = session.beginTransaction();
		try {
			Object ret = session.save(or);
			boolean res = ret != null ? true : false;
			return res;
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}

	}

	public void deleteOrderById(int id) {
		Transaction tx = session.beginTransaction();
		try {
			Orderu sec = (Orderu) session.get(Orderu.class, id);
			session.delete(sec);
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}

	}


	public Orderu getOrderById(int id) {
		Transaction tx = session.beginTransaction();
		try {
			Orderu sec = (Orderu) session.get(Orderu.class, id);
			return sec;
		} catch (Exception e) {
			tx.rollback();
			tx = null;
			throw new RuntimeException(e);
		} finally {
			if (tx != null) {
				tx.commit();
			}
		}

	}

	public Session closeSession() {
		try {
			if (session != null) {
				session.flush();
				session.clear();
			}
			return session;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			session = null;
		}
	}
}
